import { Body, Controller, Get, Post ,Headers,UseGuards,Request } from '@nestjs/common';
import { AppService } from './app.service';
import { Cron } from '@nestjs/schedule';
import { Public } from 'src/common/public.decorator';
import { AuthService } from './auth/auth.service';
import { AuthGuard } from '@nestjs/passport';
import { AuthActionVerb, AuthPossession, AuthZGuard, AuthZRBACService, UsePermissions } from 'nest-authz';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService,
    private readonly rbacSrv: AuthZRBACService) {}

  @Public()
  @Post('/login')
  async login(@Body() body: any): Promise<any> {
    let response = await fetch('http://localhost:3000/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: body.username,
        password: body.password,
      }),
    })
    let data = await response.json();
    if (data.code == 0 || data.code == "0") {
      console.log("返回token")
      let res =  {
        success: true,
        data: {
          username: body.username,
          roles: ['admin'],
          accessToken: data.msg,
          maxAge: 60,
          refreshToken: 'mockedRefreshedToken.adminRefresh',
        }
      };
      console.log(res);
      return res;
    }
  }

  @Get('/routers')
  async routers(): Promise<any> {
    return {
      success: true,
      data: [
        {
          name: 'demo',
          path: '/admin/demo',
          meta: {
            title: '演示demo',
            icon: 'i-carbon-tool-box',
          },
          children: [
            {
              name: 'demo-table',
              path: '/admin/demo/table',
              meta: {
                title: '表格用法',
                icon: 'i-carbon-cross-tab',
              },
              children: [
                {
                  name: 'demo-table-draggable',
                  path: '/admin/demo/table/draggable',
                  meta: {
                    title: '可拖拽表格',
                    icon: 'i-carbon-move',
                  },
                },
                {
                  name: 'demo-table-inline-edit',
                  path: '/admin/demo/table/inline-edit',
                  meta: {
                    title: '行内编辑',
                    icon: 'i-ep-edit-pen',
                  },
                },
                {
                  name: 'demo-table-dynamic-row',
                  path: '/admin/demo/table/dynamic-row',
                  meta: {
                    title: '动态增减行',
                    icon: 'i-carbon-row-insert',
                  },
                },
              ],
            },
            {
              name: 'demo-element-plus',
              path: '/admin/demo/element-plus',
              meta: {
                title: 'Element 组件',
                icon: 'i-ep-element-plus',
              },
            },
            {
              name: 'demo-china-area-cascader',
              path: '/admin/demo/china-area-cascader',
              meta: {
                title: '省市区选择器',
                icon: 'i-carbon-map',
              },
            },
            {
              name: 'demo-count-up',
              path: '/admin/demo/count-up',
              meta: {
                title: '数字动画',
                icon: 'i-carbon-character-whole-number',
              },
            },
            {
              name: 'demo-scroll-notice',
              path: '/admin/demo/scroll-notice',
              meta: {
                title: '滚动通知',
                icon: 'i-carbon-star-review',
              },
            },
            {
              name: 'demo-animate-background',
              path: '/admin/demo/animate-background',
              meta: {
                title: '动画页面背景',
                icon: 'i-ep-magic-stick',
              },
            },
            {
              name: 'demo-pdf',
              path: '/admin/demo/pdf',
              meta: {
                title: 'PDF 预览',
                icon: 'i-carbon-document-pdf',
              },
            },
            {
              name: 'demo-tinyMCE',
              path: '/admin/demo/tinyMCE',
              meta: {
                title: '富文本编辑器',
                icon: 'i-carbon-language',
              },
            },
            {
              name: 'demo-icon',
              path: '/admin/demo/icon',
              meta: {
                title: 'Iconify 在线图标',
                icon: 'i-carbon-face-satisfied',
              },
            },
          ],
        },
        {
          name: 'password',
          path: '/admin/password',
          meta: {
            title: '密码',
            icon: 'i-carbon-tool-box',
          },
          children: [
            {
              name: 'passwordRe',
              path: '/admin/password/password',
              meta: {
                title: '密码更改',
                icon: 'i-ep-element-plus',
              },
            },
          ],
        },
        {
          name: 'table',
          path: '/admin/table',
          meta: {
            title: '数据表格',
            icon: 'i-carbon-tool-box',
          },
          children: [
            {
              name: 'tableDate',
              path: '/admin/table/table',
              meta: {
                title: '数据表格',
                icon: 'i-ep-element-plus',
              },
            },
          ],
        },
        {
          name: 'echarts',
          path: '/admin/echarts',
          meta: {
            title: '数据图表',
            icon: 'i-carbon-tool-box',
          },
          children: [
            {
              name: 'tableDate',
              path: '/admin/echarts/echarts',
              meta: {
                title: '数据图表',
                icon: 'i-ep-element-plus',
              },
            },
            {
              name: 'tubiao',
              path: '/admin/tubiao/tubiao',
              meta: {
                title: '3D图表',
                icon: 'i-ep-element-plus',
              },
            },
          ],
        },
        {
          name: 'sync',
          path: '/admin/sync',
          meta: {
            title: '同步设置',
            icon: 'i-carbon-tool-box',
          },
          children: [
            {
              name: 'syncsetting',
              path: '/admin/sync/sync',
              meta: {
                title: '同步设置',
                icon: 'i-ep-element-plus',
              },
            },
          ],
        },
      ],
    };
  }

  @Get('/sync')
  @UseGuards(AuthGuard('jwt'), AuthZGuard)
  @UsePermissions({
    action: AuthActionVerb.READ,
    resource: "USER",
    possession: AuthPossession.OWN_ANY,
    isOwn: (req: any): boolean => {
      console.log("用户名", req.getRequest().user.role)
      if(req.getRequest().user.role == "USER"){
        return true;
      }else{
        return false;
      }

    },
  })
  async getSync(): Promise<string> {
    await this.appService.sync();
    return '';
  }

  @Get('/getAddress')
  @UseGuards(AuthGuard('jwt'), AuthZGuard)
  @UsePermissions({
    action: AuthActionVerb.READ,
    resource: "USER",
    possession: AuthPossession.OWN_ANY,
    isOwn: (req: any): boolean => {
      console.log("用户名", req.getRequest().user.role)
      if(req.getRequest().user.role == "USER"){
        return true;
      }else{
        return false;
      }

    },
  })
  async getAddress(): Promise<string> {
    const res = await this.appService.getAddressInfo();
    return res;
  }
  


  @Cron('10 * * * * *')
  async handleCron() {
    await this.appService.sync();
  }

  @UseGuards(AuthGuard('jwt'))
  @Post("/revise")
  async revise(@Body() body: any, @Request() req): Promise<any> {
    console.log("用户名", req.user.username);
    console.log("用户名", req.user)
    body.username = req.user.username
    return this.appService.revise(body,req.user.username );
  }
}
